import axios from 'axios'; // 引入axios
import {Message} from 'element-ui';
import context from '../main'

const service = axios.create({
    baseURL: process.env.VUE_APP_BASE_API,
    withCredentials: true,
    timeout: 20000

})

//http request 拦截器
service.interceptors.request.use(
    config => {
        config.headers = {
            'x-token': localStorage.getItem("login_token"),
        }
        if (config.params) {
            for (let key in config.params) {
                if (config.params[key] == '' || config.params[key] == undefined) {
                    delete config.params[key];
                }
            }
        }
        if (config.data) {
            for (let key in config.data) {
                if (config.data[key] == '' || config.data[key] == undefined) {
                    delete config.data[key];
                }
            }
        }
        return config;
    },
    error => {
        console.error(error)
        Message({
            showClose: true,
            message: error,
            type: 'error'
        })
        return Promise.reject(error);

    }
);


//http response 拦截器
service.interceptors.response.use(
    response => {
        if (response.status == "200") {
            if (response.data) {
                if (response.config.responseType == 'blob') {
                    return response;
                }
                return response.data;
            }
            return null;
        } else {
            console.error(response)
            Message({
                showClose: true,
                message: response.data.errCode + ":" + response.data.errMsg,
                type: response.data || 'error',
            })
            return Promise.reject(response.status);
        }
    },
    error => {
        console.error(error)
        if (error.response.data && error.response.data.errCode == 401) {
            context.$router.push("/login");
        } else {
            Message({
                showClose: true,
                message: error.response.data.errCode + ":" + error.response.data.errMsg,
                type: 'error'
            })
        }
        return Promise.reject(error);
    }
)

export default service